package com.example.chat01.config;

import com.example.chat01.ws.User;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptor;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

import java.security.Principal;

@Configuration
//开启消息代理
@EnableWebSocketMessageBroker
public class WsConfig implements WebSocketMessageBrokerConfigurer {
    /**
     * 这个地方相当于配置 ws 的连接点
     * @param registry
     */
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry
                //配置连接点，浏览器将来就发送消息给这个端点
                .addEndpoint("/myws/ep")
                //设置 websocket 链接允许的源，即从哪里发送来的
                .setAllowedOriginPatterns("*")
                //前端支持 sockjs 库
                .withSockJS();
    }

    /**
     * 配置消息代理，哪些位置的消息，将来要通过 Spring 进行代理
     * @param registry
     */
    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        //将来发消息的时候，如果消息发送目标地址是 /topic 或者 /queue 开始的，则消息转交给 Spring 去代理
        registry.enableSimpleBroker("/topic", "/queue");
        registry.setApplicationDestinationPrefixes("/app");
    }

//    // 如果没有引入security，则需要自己手动配置通道拦截器设置 连接会话的 用户
//    @Override
//    public void configureClientInboundChannel(ChannelRegistration registration) {
//        registration.interceptors(new ChannelInterceptor() {
//
//            @Override
//            public Message<?> preSend(Message<?> message, MessageChannel channel) {
//                StompHeaderAccessor accessor =
//                        MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
//
//                if (StompCommand.CONNECT.equals(accessor.getCommand())) {
//                    // 手动指定,实际项目中 name 可以指定为当前登录用户名
//                    String name = "zs";
//                    Principal user = new User(name); // access authentication header(s)
//                    accessor.setUser(user);
//                }
//                return message;
//            }
//        });
//    }

}
